package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.TCloudClass;
import model.VClassInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 班级管理请求处理类
 * @author 徐震霖
 */
@Controller
@RequestMapping(value = "/sysclassmanagement")
public class SysClassManagementController {

	/**
	 * 根据开班年份生成班级id（如：YNKMYTXX20170901001）和 生成班级编号（如：1班、2班、3班等）处理类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 根据开班年份生成班级id（如：YNKMYTXX20170901001）和 生成班级编号（如：1班、2班、3班等）处理类
	@RequestMapping(value = "/createclassid")
	public String createClassid(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			String gradeYear = req.getParameter("gradeYear");
			String stage = req.getParameter("stage");
			String schoolid = req.getParameter("schoolid");
			if (gradeYear != null && !gradeYear.equals("") && stage != null && !stage.equals("")) {
				String year = gradeYear;
				gradeYear += "-09-01";
				String classid = schoolid + year + "0901";
				if (stage.trim().equals("小学")) {
					classid += "01";// 加入01为小学代码
				} else if (stage.trim().equals("初中")) {
					classid += "02";// 加入02为初中代码
				} else {
					classid += "03";// 加入03为高中代码
				}
				exp.andEqu("gradeYear", gradeYear, String.class);
				exp.andEqu("schoolid", schoolid, String.class);
				exp.andEqu("period", stage, String.class);

				String strWhere = exp.toString();
				List<VClassInfo> classList = DAOFactory.getCloudClassDAO().getClassList(strWhere);
				if (classList != null && classList.size() > 0) {
					if (classList.size() > 0 && classList.size() < 10) {
						classid += "00" + (classList.size() + 1);
					} else if (classList.size() > 10 && classList.size() < 100) {
						classid += "0" + (classList.size() + 1);
					} else {
						classid += (classList.size() + 1) + "";
					}
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "获取成功！");
					result.put("classid", classid);// 班级id生成返回
					result.put("classNumber", (classList.size() + 1) + "班");// 班级编号生成返回

				} else {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "获取成功！");
					result.put("classid", classid + "001");// 班级id生成返回
					result.put("classNumber", "1班");// 班级编号生成返回
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "开班年份或阶段不能为空，班级id生成失败！");
			}

		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现错误，班级id生成失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 根据开班年份得到班级信息处理类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 根据开班年份得到班级信息处理类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据开班年份查询班级信息", operationClassPath = "controller.SysClassManagementController.getClassByGradeYear(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息添加")
	@RequestMapping(value = "/getclassbygradeyear")
	public String getClassByGradeYear(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression exp = new Expression();

		try {
			String gradeYear = req.getParameter("gradeYear");
			String schoolid = req.getParameter("schoolid");
			if (gradeYear != null && !gradeYear.equals("")) {
				gradeYear += "-09-01";
				exp.andEqu("gradeYear", gradeYear, String.class);
			}
			if (schoolid != null && !schoolid.equals("")) {
				exp.andEqu("schoolid", schoolid, String.class);
			}
			String strWhere = exp.toString();
			List<VClassInfo> classList = DAOFactory.getCloudClassDAO().getClassList(strWhere);
			if (classList != null && classList.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", classList.size());
				JSONArray jsonArray = JSONArray.fromObject(classList);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "未获取到班级信息");
			}

		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现错误，未获取到班级信息，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 添加班级处理类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 添加班级处理类
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个班级信息", operationClassPath = "controller.SysClassManagementController.addClass(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息添加")
	@RequestMapping(value = "/addclass")
	public String addClass(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TCloudClass clTClass = new TCloudClass();

		try {
			String classid = req.getParameter("classid");// 班级id
			String classnumber = req.getParameter("classnumber");// 班级编号
			String className = req.getParameter("className");// 班级名称
			String gradeYear = req.getParameter("gradeYear");// 入学年份
			String period = req.getParameter("period");// 所属阶段
			String schoolid = req.getParameter("schoolid");

			if (classid != null && !classid.equals("") && className != null && !className.equals("")
					&& gradeYear != null && !gradeYear.equals("") && period != null && !period.equals("")
					&& classnumber != null && !classnumber.equals("")) {

				clTClass.setClassid(classid);
				clTClass.setClassName(className);
				clTClass.setGradeYear(gradeYear);
				clTClass.setPeriod(period);
				clTClass.setClassNumber(classnumber);
				clTClass.setSchoolid(schoolid);

			}

			int row = DAOFactory.getCloudClassDAO().addClass(clTClass);
			if (row > 0) {
				result.put("code", ResponseJSON.FLAG_SUCC);
				result.put("msg", "添加成功！");
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "添加失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，添加失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}

	/**
	 * 修改班级信息
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 修改班级信息
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个班级信息", operationClassPath = "controller.SysClassManagementController.updateClass(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息查看")
	@RequestMapping(value = "/updateclass")
	public String updateClass(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		TCloudClass clTClass = null;

		try {
			String classid = req.getParameter("classid");// 班级编号
			String className = req.getParameter("className");// 班级名称
			String gradeYear = req.getParameter("gradeYear");// 入学年份
			if (classid != null && !classid.equals("") && className != null && !className.equals("")
					&& gradeYear != null && !gradeYear.equals("")) {
				clTClass = DAOFactory.getCloudClassDAO().getTClass(classid);

				clTClass.setClassName(className);
				clTClass.setGradeYear(gradeYear);
				boolean row = DAOFactory.getCloudClassDAO().updateClass(clTClass);
				if (row) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "修改成功!");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "修改失败，请重试！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "修改失败，必填项不能为空！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "出现异常，修改失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 班级信息查询
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 班级信息查询
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询班级信息", operationClassPath = "controller.SysClassManagementController.getClassByStrWhere(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息查看")
	@RequestMapping(value = "/getclassbystrwhere")
	public String getClassByStrWhere(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression ex = new Expression();

		int currentPage = 1;
		int pageSize = 10;

		try {
			String schoolid = req.getParameter("schoolid");
			String grade = req.getParameter("grade");
			String classid = req.getParameter("classid");
			String page = req.getParameter("page");
			if (page != null && !page.equals("")) {
				currentPage = Integer.parseInt(page);
			}
			String limit = req.getParameter("limit");
			if (limit != null && !limit.equals("")) {
				pageSize = Integer.parseInt(limit);
			}
			if (schoolid != null && !schoolid.equals("")) {
				ex.andEqu("schoolid", schoolid, String.class);
			}

			if (grade != null && !grade.equals("")) {
				ex.andEqu("gradename", grade, String.class);
			}
			if (classid != null && !classid.equals("")) {
				ex.andLeftBraLike("classid", classid, String.class);
				ex.orRightBraLike("className", classid, String.class);
			}

			String strWhere = ex.toString();
			List<VClassInfo> list = DAOFactory.getCloudClassDAO().getClassListPage(strWhere, currentPage, pageSize);
			List<VClassInfo> listSize = DAOFactory.getCloudClassDAO().getClassList(strWhere);

			if (list != null && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listSize.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (NumberFormatException e) {
			result.put("code", 2);
			result.put("msg", "出现异常，查询失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 得到某个学校的所有班级
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 得到某个学校的所有班级
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询某个学校的所有班级", operationClassPath = "controller.SysClassManagementController.getAllClass(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息查看")
	@RequestMapping(value = "/getallclass")
	public String getAllClass(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression ex = new Expression();

		try {
			String schoolid = req.getParameter("schoolid");
			ex.andEqu("schoolid", schoolid, String.class);
			ex.orderByAsc("gradename");
			String strWhere = ex.toString();
			List<VClassInfo> listSize = DAOFactory.getCloudClassDAO().getClassList(strWhere);

			if (listSize != null && listSize.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listSize.size());
				JSONArray jsonArray = JSONArray.fromObject(listSize);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (NumberFormatException e) {
			result.put("code", 2);
			result.put("msg", "出现异常，查询失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 得到某个年级的全部班级
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 得到某个年级的全部班级
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询某个年级的所有班级", operationClassPath = "controller.SysClassManagementController.getClassByGrade(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息查看")
	@RequestMapping(value = "/getclassbygrade")
	public String getClassByGrade(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression ex = new Expression();

		try {
			String schoolid = req.getParameter("schoolid");
			String grade = req.getParameter("grade");
			ex.andEqu("schoolid", schoolid, String.class);
			ex.andEqu("gradename", grade, String.class);
			String strWhere = ex.toString();
			List<VClassInfo> listSize = DAOFactory.getCloudClassDAO().getClassList(strWhere);

			if (listSize != null && listSize.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listSize.size());
				JSONArray jsonArray = JSONArray.fromObject(listSize);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (NumberFormatException e) {
			result.put("code", 2);
			result.put("msg", "出现异常，查询失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 根据学校和年级查询得到班信息(年级和学校)
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 * @author djf
	 * @since 2018/12/9
	 */
	// TODO 根据学校和年级查询得到班信息(年级和学校)
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据学校和年级查询班级", operationClassPath = "controller.SysClassManagementController.getClassBySchoolAndGrade(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "学生管理/学生信息添加")
	@RequestMapping(value = "/getclassbyschoolandgrade")
	public String getClassBySchoolAndGrade(Model model, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		Expression ex = new Expression();

		try {
			String schoolid = req.getParameter("schoolid");
			String gradename = req.getParameter("gradename");
			if (schoolid != null && !schoolid.equals("")) {
				ex.andEqu("schoolid", schoolid, String.class);
			}
			if (gradename != null && !gradename.equals("")) {
				ex.andEqu("gradename", gradename, String.class);
			}

			String strWhere = ex.toString();
			List<VClassInfo> listSize = DAOFactory.getCloudClassDAO().getClassList(strWhere);

			if (listSize != null && listSize.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listSize.size());
				JSONArray jsonArray = JSONArray.fromObject(listSize);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果！");
			}
		} catch (NumberFormatException e) {
			result.put("code", 2);
			result.put("msg", "出现异常，查询失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

	/**
	 * 班级信息删除控制类
	 * 
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	// TODO 班级信息删除控制类
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个班级信息", operationClassPath = "controller.SysClassManagementController.deleteClass(Model model, HttpServletRequest req, HttpServletResponse resp)", operationMenu = "班级管理/班级信息查看")
	@RequestMapping(value = "/deleteclass")
	public String deleteClass(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {

		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();

		try {
			String classid = req.getParameter("classid");
			if (classid != null && !classid.equals("")) {
				if (DAOFactory.getCloudClassDAO().deleteClass(classid)) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "删除成功！");
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "存在外键引用，请删除引用后重试！");
				}
			} else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "删除失败，班级编号不能为空！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "存在外键引用，请删除引用后重试！");
			e.printStackTrace();
		}

		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;

	}

}
